﻿using DongFangGuoKai.WMSPlatform.Domain.Enum;
using DongFangGuoKai.WMSPlatform.Domain.Model;
using DongFangGuoKai.WMSPlatform.Service.InboundOrderDetail.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DongFangGuoKai.WMSPlatform.Service.InboundOrderDetail
{
    public partial class TReceivingOrderDetailService
    {
        protected readonly static object _lockObj = new object();
        /// <summary>
        /// 可以组多个物料
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool BuildCreateStackingStorageMaterials(ReceivingBillOrderMaterialsDto m, out string message)
        {
            message = "";
            try
            {
                receivingbillrepost.AsTenant().BeginTran();
                var receivingBills = receivingbillrepost.GetFirst(r => r.Id == m.Id);
                if (receivingBills == null)
                {
                    message = "收货单不存在";
                    return false;
                }
                var rbd = receivingbillDteailrepost.GetList(x => x.BillId == receivingBills.Id);

                //计算已收货数量
                receivingBills.ReceivedQTY = receivingBills.ReceivedQTY + rbd.Sum(r => r.ReceivedQty);

                string receordercode = ""; //入库单号

                //查看收货单已收货数量是否是0 （是的话创建一个入库单编号 不是0查询出入库单编号）
                if (receivingBills.ReceivedQTY == 0 || receivingBills.ReceivedQTY is null)
                {
                    receivingBills.WarehouseId = m.StoreId;
                    
                    receordercode = GetInOrderBarCode();
                    if (string.IsNullOrEmpty(receordercode) || receordercode.Length == 0)
                    {
                        message = "入库单号生成失败！";
                        return false;
                    }
                }
                else
                {
                    var rece = receivingOrderDetailsrepost.GetFirst(r => r.ReceivingBillId == receivingBills.Id);
                    if (rece is null)
                    {
                        message = "未查询到入库单号";
                        receivingbillrepost.AsTenant().RollbackTran();
                        return false;
                    }
                    receordercode = rece.OrderSn;
                }

                decimal count = 0;//计算数量
                foreach (var item in m.ReceivingBillOrderMaterialsDetailDto)
                {
                    if (item.ReceivedQty < 0)
                    {
                        message = "收货数量不能小于0";
                        receivingbillrepost.AsTenant().RollbackTran();
                        return false;
                    }

                    var r = receivingbillDteailrepost.GetFirst(r => r.Id == item.ReceivingBillDetailId);
                    if (r is null)
                    {
                        message = "收货单明细不存在";
                        receivingbillrepost.AsTenant().RollbackTran();
                        return false;
                    }

                    item.MaterialName = r.MaterialName;
                    item.MaterialBatchNo = r.BatchNo;
                    item.DeptName = r.deptName;
                    item.CheckInfoId = r.checkInfoId;

                    //计算总数量
                    if (r.Qty >= item.ReceivedQty && (r.ReceivedQty + item.ReceivedQty) <= r.Qty)
                    {
                        r.ReceivedQty += item.ReceivedQty;
                        count += item.ReceivedQty;
                        if (r.Price != null && r.Price >= 0)
                        {
                            receivingBills.TotalPrice += (decimal)r.Price * item.ReceivedQty;
                        }
                    }
                    else
                    {
                        message = "收货数量不能大于物料数量！";
                        receivingbillrepost.AsTenant().RollbackTran();
                        return false;
                    }

                    if (!receivingbillDteailrepost.Update(r))
                    {
                        message = "修改收获单明细失败！";
                        receivingbillrepost.AsTenant().RollbackTran();
                        return false;
                    }
                }


                bool reresult = false;

                //获取验收单明细数据
                var res = receivingbillDteailrepost.GetList(x => x.BillId == receivingBills.Id).ToList();
                // 计算收货数量
                count = res.Sum(r => r.ReceivedQty);

                //查看验收单是否完成
                if (count == receivingBills.TotalQty)
                {
                    receivingBills.Status = 2;
                    receivingBills.EndDate = DateTime.Now;
                }
                if (count < receivingBills.TotalQty)
                {
                    receivingBills.Status = 1;
                }
                //修改验收单状态
                if (!receivingbillrepost.Update(receivingBills))
                {
                    message = "修改收货单失败";
                    receivingbillrepost.AsTenant().RollbackTran();
                    return false;
                }

                reresult = AddReceivingOrderDeatils(m, receordercode, out message);
                if (reresult == false)
                {
                    message = message;
                    receivingbillrepost.AsTenant().RollbackTran();
                    return false;
                }

                //查询组垛数据并入库
                var cell = cellrepost.GetFirst(c => c.Code == m.StoreLocationCode && c.Status == 1);
                if (cell is null)
                {
                    message = "未找到此仓位";
                    return false;
                }
                var stackingStorages = stackingstoragesrepost.GetList(s => s.Status == 1 && s.ExpectedLocation == cell.Code);
                if (stackingStorages.Count() <= 0)
                {
                    message = "组垛数据有误";
                    receivingbillrepost.AsTenant().RollbackTran();
                    return false;
                }
                foreach (var stackingStorage in stackingStorages)
                {
                    var orderDetail = receivingOrderDetailsrepost.GetFirst(x => x.Id == stackingStorage.RelatedOrderDetailId);
                    PalletBindMaterialModel palletBindMaterialModel = new PalletBindMaterialModel()
                    {
                        StackingStorageId = stackingStorage.Id,
                        MaterialPackageBindModel = new MaterialPackageBindModel()
                        {
                            OrderDetailId = orderDetail.Id,
                            MaterialCode = orderDetail.MaterialCode,
                            Qty = orderDetail.Qty,
                        }
                    };
                    reresult = ExecCreateMaterialsInstruct(out message, orderDetail, palletBindMaterialModel);
                    if (reresult == false)
                    {
                        message = "入库失败，" + message;
                        receivingbillrepost.AsTenant().RollbackTran();
                        return false;
                    }
                }

                //提交事务
                receivingbillrepost.AsTenant().CommitTran();
                return true;
            }
            catch (Exception ex)
            {
                message = "保存失败，" + ex.Message;
                receivingbillrepost.AsTenant().RollbackTran();
                return false;
            }
        }

        /// <summary>
        /// 添加入库单和组垛数据
        /// </summary>
        /// <param name="m"></param>
        /// <param name="receordercode"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool AddReceivingOrderDeatils(ReceivingBillOrderMaterialsDto m, string receordercode, out string message)
        {
            var cell = cellrepost.GetFirst(c => c.Code == m.StoreLocationCode && c.Status == 1);
            if (cell is null)
            {
                message = "未找到此仓位";
                return false;
            }
            //不需要托盘
            //var pallet = palletsrepost.GetFirst(p=>p.PalletBarcode == m.PalletBarcode && p.Status == 1);
            //if (pallet == null)
            //{
            //    message = "未找到此托盘";
            //    return false;
            //}
            //bool reresult = false;
            message = "";
            foreach (var item in m.ReceivingBillOrderMaterialsDetailDto)
            {
                TReceivingOrderDetails receivingOrder = new TReceivingOrderDetails();
               
                #region 添加入库单数据
                receivingOrder.OrderSn = receordercode;
                //本地入库
                receivingOrder.BillType = 1;
                receivingOrder.WarehouseId = m.StoreId;
                //receivingOrder.SupplierId = m.Suppid;
                receivingOrder.MaterialId = item.MaterialId;
                receivingOrder.MaterialCode = item.MaterialCode;
                receivingOrder.MaterialName = item.MaterialName;
                receivingOrder.OwnerId = item.OwerId;
                receivingOrder.BatchNo = item.MaterialBatchNo;
                receivingOrder.DeptName = item.DeptName;
                //订单来源默认手动创建
                receivingOrder.SourceType = 0;
                //质检状态默认为合格
                receivingOrder.QualityState = 1;
                //质量状态
                receivingOrder.Status = 3;
                receivingOrder.ReceivedQty = 0;
                receivingOrder.PackagedQty = 0;
                receivingOrder.PackQty = 0;
                receivingOrder.BatchNoExplain = item.BatchNoExplain;
                receivingOrder.OutFactoryDate = item.OutFactoryDate;
                receivingOrder.ProduceFactory = item.ProduceFactory;
                receivingOrder.ProductDate = item.ProductDate;
                receivingOrder.ExpireDate = item.ExpireDate;
                receivingOrder.Remark = item.Remark;
                receivingOrder.Qty = item.ReceivedQty;
                receivingOrder.storeLocationId = cell.Erpcode;
                receivingOrder.relationId = item.CheckInfoId.GetValueOrDefault();
                receivingOrder.CreateUserId = m.NowUserId;
                receivingOrder.CreateUserName = m.NowUserRealName;
                receivingOrder.CreateDate = DateTime.Now;
                receivingOrder.AuditUserId = m.NowUserId;
                receivingOrder.AuditUserName = m.NowUserRealName;
                receivingOrder.AuditDate = DateTime.Now;
                receivingOrder.SubmitUserId = m.NowUserId;
                receivingOrder.SubmitUserName = m.NowUserRealName;
                receivingOrder.SubmitDate = DateTime.Now;
                receivingOrder.ReceivingBillId = m.Id;
                //采购订单行项目类型
                receivingOrder.PurOrderLineType = 0;
                receivingOrder.StackedQty = item.ReceivedQty;
                #endregion

                receivingOrder.Id = receivingOrderDetailsrepost.InsertReturnIdentity(receivingOrder);
                if (receivingOrder.Id <= 0)
                {
                    message = "添加入库单失败！";
                    return false;
                }

                #region 垛包装数据保存
                TStackingStorages chStacking = new TStackingStorages();
                chStacking.WarehouseName = receivingOrder.WarehouseName;
                chStacking.WarehouseCode = receivingOrder.WarehouseCode;
                chStacking.BillType = (int)receivingOrder.BillType.GetValueOrDefault();
                chStacking.RelatedOrderDetailId = receivingOrder.Id;
                chStacking.Status = 1;
                chStacking.Qty = item.ReceivedQty; //一个物资的明细的收货数量等一一个入库单的总数量
                chStacking.PackQty = 1;
                chStacking.AreaCode = receivingOrder.AreaCode;
                chStacking.MaterialId = receivingOrder.MaterialId;
                chStacking.MaterialCode = receivingOrder.MaterialCode;
                chStacking.MaterialName = receivingOrder.MaterialName;
                chStacking.CreateUserId = m.NowUserId;
                chStacking.CreateUserName = m.NowUserRealName;
                chStacking.BatchNo = receivingOrder.BatchNo;
                chStacking.CreateDate = DateTime.Now;
                chStacking.Fifodate = DateTime.Now;
                chStacking.ExpectedLocation = cell.Code;
                chStacking.cellName = cell.Name;
                chStacking.WarehouseId = receivingOrder.WarehouseId.GetValueOrDefault();
                chStacking.cellId = Convert.ToInt32(cell.Erpcode);
                chStacking.AreaCode = receivingOrder.AreaCode;
                chStacking.AreaName = receivingOrder.AreaName;
                #endregion

                if (!stackingstoragesrepost.Insert(chStacking))
                {
                    message = "保存垛主表数据失败";
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 添加组垛数据多个(物料使用的)
        /// </summary>
        /// <param name="errMsg"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private bool CreateCompleteStacking(out string errMsg, PalletTallyInputModel data)
        {
            errMsg = string.Empty;
           
            try
            {
                //查询仓位是否已被使用
                var inventory = inventoriesrepost.GetFirst(i => i.LocationId == data.storeLocationId);
                if (inventory is not null)
                {
                    errMsg = "仓位已存在," + data.storeLocationId;
                    return false;
                }
                //查看托盘是否已被使用
                inventory = inventoriesrepost.GetFirst(i => i.PalletBarcode == data.PalletBarcode);
                if (inventory is not null)
                {
                    errMsg = "托盘已存在," + data.PalletBarcode;
                    return false;
                }
                //下面代码放在了AddReceivingOrderDeatils方法中


                return true;
            }
            catch (Exception)
            {
                errMsg = "保存组箱数据失败";
                return false;
            }
           
        }


        /// <summary>
        /// 入库(多个物料的) （海宁的）
        /// </summary>
        /// <param name="Palletlist">托盘码</param>
        /// <returns></returns>
        public bool ExecCreateMaterials(string PalletCode, out string errMsg)
        {
            try
            {
                errMsg = "";
                //查询托盘
                var pallet = palletsrepost.GetFirst(p=>p.PalletBarcode == PalletCode && p.Status == 1);
                if( pallet == null )
                {
                    errMsg = "未查询到托盘";
                    return false;
                }
                var stackingStorages = stackingstoragesrepost.GetList(s => s.Status == 1 && s.PalletBarcode == PalletCode);
                if (stackingStorages.Count() <= 0)
                {
                    errMsg = "组垛数据有误";
                    return false;
                }
                receivingbillrepost.AsTenant().BeginTran();
                foreach (var stackingStorage in stackingStorages)
                {
                    var orderDetail = receivingOrderDetailsrepost.GetFirst(x => x.Id == stackingStorage.RelatedOrderDetailId);
                    PalletBindMaterialModel palletBindMaterialModel = new PalletBindMaterialModel()
                    {
                        StackingStorageId = stackingStorage.Id,
                        MaterialPackageBindModel = new MaterialPackageBindModel()
                        {
                            OrderDetailId = orderDetail.Id,
                            MaterialCode = orderDetail.MaterialCode,
                            Qty = orderDetail.Qty,
                        }
                    };
                    var result = ExecCreateMaterialsInstruct(out errMsg, orderDetail, palletBindMaterialModel);
                    if (result == false)
                    {
                        errMsg = "入库失败，" +errMsg;
                        receivingbillrepost.AsTenant().RollbackTran();
                        return false;
                    }
                }
                receivingbillrepost.AsTenant().CommitTran();
                return true;
            }
            catch (Exception ex)
            {
                errMsg = "入库失败，" + ex.Message;
                receivingbillrepost.AsTenant().RollbackTran();
                return false;
            }
        }

        /// <summary>
        /// 开始入库（多个物料的）
        /// </summary>
        /// <param name="errorMsg"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool ExecCreateMaterialsInstruct(out string errorMsg, params object[] data)
        {
            errorMsg = "";
            if (data == null || data.Length < 2)
            {
                errorMsg = "参数错误";
                return false;
            }
            lock (_lockObj)
            {
                try
                {
                    TReceivingOrderDetails orderDetail = data[0] as TReceivingOrderDetails;
                    PalletBindMaterialModel palletBind = data[1] as PalletBindMaterialModel;
                    if (orderDetail == null || palletBind == null)
                    {
                        errorMsg = "参数错误";
                        return false;
                    }
                    TCells allocateCell = null;
                    decimal? materialNum = 0;

                    #region 校验入库单
                    if (orderDetail.Status == (int)EmBillStatus.Create)
                    {
                        errorMsg = "入库单未启动";
                        return false;
                    }
                    if (orderDetail.Status == (int)EmBillStatus.Finished || orderDetail.Status == (int)EmBillStatus.MandatoryFinished)
                    {
                        errorMsg = "入库单已完成";
                        return false;
                    }
                    if (orderDetail.Status != (int)EmBillStatus.Executing)
                    {
                        errorMsg = "当前入库单未执行";
                        return false;
                    }
                    #endregion

                    var stackingstorage = stackingstoragesrepost.GetFirst(s => s.Id == palletBind.StackingStorageId && s.Status == 1 && s.RelatedOrderDetailId == orderDetail.Id);
                    if (stackingstorage == null)
                    {
                        errorMsg = "未查询到组垛数据";
                        return false;
                    }
                    stackingstorage.Status = 2;
                    if (!stackingstoragesrepost.Update(stackingstorage))
                    {
                        errorMsg = "修改组垛数据失败";
                        return false;
                    }

                    allocateCell = cellrepost.GetFirst(c => c.Code == stackingstorage.ExpectedLocation);
                    if (allocateCell == null)
                    {
                        errorMsg = "仓位不存在";
                        return false;
                    }

                    //最小库存单位
                    materialNum = palletBind.MaterialPackageBindModel.Qty;
                    bool hasSkuDetail = true;
                    DateTime? now = DateTime.Now;
                    decimal StartQty = 0;

                    //查看仓位和托盘上是否存在该物资 如果存在则加数量不存在则新增一条库存数据
                    var inventoryData = inventoriesrepost.GetFirst(i=>i.MaterialCode == stackingstorage.MaterialCode && i.LocationCode == allocateCell.Code);
                    if (inventoryData == null)
                    {
                        //保存库存
                        TInventories inventory = new TInventories()
                        {
                            WarehouseId = stackingstorage.WarehouseId,
                            WarehouseCode = allocateCell.WhCode,
                            WarehouseName = allocateCell.WhName,
                            AreaCode = allocateCell.AreaCode,
                            AreaName = allocateCell.AreaName,
                            LocationId = stackingstorage.cellId,
                            LocationCode = stackingstorage.ExpectedLocation,
                            //LocationDepth = allocateCell.DepthIndex,
                            LocationName = stackingstorage.cellName,
                            Status = 1,
                            //PalletBarcode = palletBarcode,//不需要托盘
                            ParentPalletBarcode = stackingstorage.ParentPalletBarcode,
                            RelatedOrderDetailId = orderDetail.Id,
                            BillType = (int)orderDetail.BillType.GetValueOrDefault(),
                            IsLock = false,
                            CreateDate = DateTime.Now,
                            MaterialId = orderDetail.MaterialId,
                            MaterialCode = orderDetail.MaterialCode,
                            MaterialName = orderDetail.MaterialName,
                            HasSkuDetail = hasSkuDetail,
                            PutawayQty = materialNum,
                            AvailableQty = materialNum,
                            AllocateQty = materialNum,
                            UnitId = orderDetail.UnitId,
                            UnitName = orderDetail.UnitName,
                            MaterialKeyId = orderDetail.MaterialKeyId,
                            BatchNo = orderDetail.BatchNo,
                            OwnerId = orderDetail.OwnerId,
                            OwnerName = orderDetail.OwnerName,
                            ExpireDate = orderDetail.ExpireDate,
                            ProductDate = orderDetail.ProductDate,
                            SupplierId = orderDetail.SupplierId,
                            SupplierName = orderDetail.SupplierName,
                            MaterialTypeCode = orderDetail.MaterialTypeCode,
                            MaterialTypeName = orderDetail.MaterialTypeName,
                            PickedQty = 0,
                            StackingStorageId = stackingstorage.Id,
                            LogicalPartCode = orderDetail.LogicalPartCode,//按单据来
                            DeptCode = orderDetail.DeptCode,
                            DeptName = orderDetail.DeptName,
                            InStockDate = now,
                            InStockShortDate = Convert.ToInt32(now.Value.ToString("yyyyMMdd"))
                        };
                        var inventoryId = inventoriesrepost.InsertReturnIdentity(inventory);
                        if (inventoryId <= 0)
                        {
                            errorMsg = "保存库存数据失败";
                            return false;
                        }
                    }
                    else
                    {
                        //修改库存数量
                        StartQty = inventoryData.PutawayQty.GetValueOrDefault();
                        inventoryData.PutawayQty += materialNum;
                        inventoryData.AllocateQty += materialNum;
                        inventoryData.AvailableQty += materialNum;
                        if (!inventoriesrepost.Update(inventoryData))
                        {
                            errorMsg = "修改库存数量失败";
                            return false;
                        }
                    }

                    //修改入库单数据
                    var receivingOrderDetail = receivingOrderDetailsrepost.GetFirst(r => r.Id == orderDetail.Id);
                    receivingOrderDetail.ReceivedQty = materialNum;
                    receivingOrderDetail.InStarDate = now;
                    receivingOrderDetail.Status = 4;
                    if (!receivingOrderDetailsrepost.Update(receivingOrderDetail))
                    {
                        errorMsg = "入库单明细修改失败";
                        return false;
                    }

                    //保存库存日志表
                    TInventoryLogs inventoryLog = new TInventoryLogs()
                    {
                        SourceType = 0,
                        SourceSn = orderDetail.OrderSn,
                        WarehouseId = orderDetail.WarehouseId,
                        WarehouseName = orderDetail.WarehouseName,
                        LocationCode = allocateCell.Code,
                        //PalletBarcode = palletBarcode,不需要托盘
                        OwnerId = orderDetail.OwnerId,
                        OwnerName = orderDetail.OwnerName,
                        MaterialId = orderDetail.MaterialId,
                        MaterialCode = orderDetail.MaterialCode,
                        MaterialName = orderDetail.MaterialName,
                        BatchNo = orderDetail.BatchNo,
                        StartQty = StartQty,
                        ChangeQty = materialNum,
                        EndQty = materialNum,
                        BaseUnitId = orderDetail.UnitId,
                        BaseUnitName = orderDetail.UnitName,
                        CreateDate = DateTime.Now,
                    };
                    if (!inventoryLogsrepost.Insert(inventoryLog))
                    {
                        errorMsg = "库存日志表保存失败";
                        return false;
                    }

                    return true;
                }
                catch (Exception ex)
                {
                    errorMsg = "入库失败，" + ex.Message;
                    return false;
                }
            }
        }

        /// <summary>
        /// 完成入库（是给多物料开始入库开始调用的）不需要回调完成入库 在开始入库就已放到库存中
        /// </summary>
        /// <param name="instruct"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        private bool ExecInstructFinishedMaterials(TInstructs instruct, out string errorMsg)
        {
            errorMsg = "";
            if (string.IsNullOrEmpty(instruct.PalletBarcode))
            {
                errorMsg = "参数错误";
                return false;
            }
            lock (_lockObj)
            {
                try
                {
                    var orderDetail = receivingOrderDetailsrepost.GetFirst(r => r.Id == instruct.RelatedOrderDetailId);
                    if (orderDetail == null)
                    {
                        errorMsg = "入库单明细不存在";
                        return false;
                    }
                    var inventory = inventoriesrepost.GetFirst(i => i.RelatedOrderDetailId == orderDetail.Id && i.LocationCode == instruct.ExpectedToLocation && i.PalletBarcode == instruct.PalletBarcode && i.Status == 3);
                    if (inventory == null)
                    {
                        errorMsg = "库存数据不存在";
                        return false;
                    }
                    List<TInventoryDetails> inventoryDetailList = inventoryDetailrepost.GetList(i => i.InventoryId == inventory.Id).ToList();
                    if (inventoryDetailList == null || inventoryDetailList.Count == 0)
                    {
                        errorMsg = "库存明细数据不存在";
                        return false;
                    }
                    List<string> packageBarcodes = inventoryDetailList.Select(t => t.PackageBarcode).Distinct().ToList();
                    DateTime? now = DateTime.Now;
                    bool result = false;

                    var putawayOrder = putawayOrderrepost.GetFirst(p => p.Status == 4 && p.RelatedOrderDetailId == orderDetail.Id && p.StackingStorageId == instruct.StackingStorageId);
                    putawayOrder.Status = 5;
                    putawayOrder.Fifodate = now;
                    if (!putawayOrderrepost.Update(putawayOrder))
                    {
                        errorMsg = "上架单状态修改失败";
                        return false;
                    }

                    var inventory1 = inventoriesrepost.GetFirst(i => i.Id == inventory.Id);
                    inventory1.Status = 1;
                    inventory1.AllocateQty = instruct.Qty;
                    inventory1.InStockDate = now;
                    inventory1.InStockShortDate = Convert.ToInt32(now.Value.ToString("yyyyMMdd"));
                    inventory1.PutawayQty = instruct.Qty;
                    inventory1.IsLock = false;
                    if (!inventoriesrepost.Update(inventory1))
                    {
                        errorMsg = "库存状态修改失败";
                        return false;
                    }
                    var cell1 = cellrepost.GetFirst(c => c.Erpcode == inventory.LocationId.ToString());
                    cell1.IsLock = false;
                    cell1.BusinessType = 0;
                    cell1.Status = 1;
                    cell1.ModifyDate = now;
                    if (!cellrepost.Update(cell1))
                    {
                        errorMsg = "仓位状态修改失败";
                        return false;
                    }
                    //查询组垛
                    decimal? totalPutawayQTY =putawayOrderrepost.GetList(t => t.SourceType == 1 && t.RelatedOrderDetailId == orderDetail.Id && t.Status == 5).Sum(t => t.Qty);
                    TReceivingOrderDetails modifyOrderDetail = new TReceivingOrderDetails
                    {
                        ReceivedQty = totalPutawayQTY,
                        InStarDate = orderDetail.InStarDate == null ? now : orderDetail.InStarDate,
                    };
                    if (totalPutawayQTY.GetValueOrDefault() >= orderDetail.Qty.GetValueOrDefault())
                    {
                        modifyOrderDetail.Status = (int)EmBillStatus.Finished;
                    }

                    var receivingOrderDetail = receivingOrderDetailsrepost.GetFirst(r => r.Id == orderDetail.Id);
                    receivingOrderDetail.ReceivedQty = modifyOrderDetail.ReceivedQty;
                    receivingOrderDetail.InStarDate = modifyOrderDetail.InStarDate;
                    receivingOrderDetail.Status = modifyOrderDetail.Status;
                    if (!receivingOrderDetailsrepost.Update(receivingOrderDetail))
                    {
                        errorMsg = "订单明细修改失败";
                        return false;
                    }

                    instruct.Status = 4;
                    if (!instructrepost.Update(instruct))
                    {
                        errorMsg = "修改指令失败";
                        receivingbillrepost.AsTenant().RollbackTran();
                        return false;
                    }

                    //保存库存日志表
                    TInventoryLogs inventoryLog = new TInventoryLogs()
                    {
                        SourceType = 0,
                        SourceSn = orderDetail.OrderSn,
                        WarehouseId = orderDetail.WarehouseId,
                        WarehouseName = orderDetail.WarehouseName,
                        AreaName = inventory.AreaName,
                        AreaId = inventory.AreaId,
                        LocationCode = inventory.LocationCode,
                        PalletBarcode = instruct.PalletBarcode,
                        OwnerId = orderDetail.OwnerId,
                        OwnerName = orderDetail.OwnerName,
                        MaterialId = orderDetail.MaterialId,
                        MaterialCode = orderDetail.MaterialCode,
                        MaterialName = orderDetail.MaterialName,
                        BatchNo = orderDetail.BatchNo,
                        StartQty = 0,
                        ChangeQty = instruct.Qty,
                        EndQty = instruct.Qty,
                        BaseUnitId = orderDetail.UnitId,
                        BaseUnitName = orderDetail.UnitName,
                        CreateDate = DateTime.Now,
                    };
                    if (!inventoryLogsrepost.Insert(inventoryLog))
                    {
                        errorMsg = "库存日志表保存失败";
                        return false;
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    errorMsg = "入库失败" + ex.Message;
                    return false;
                }
            }
        }
    }
}
